<?php
namespace App\Http\Questionnaire\Controllers;

use Illuminate\Http\Request;
use App\Http\Admin\Controllers\Controller as Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use App\Http\Questionnaire\Controllers\PageController;
use PDF;

class WordController  extends Controller
{
    public function __construct(Request $request)
    {
        $token = getToken($request);
        $uid = Redis::get("code:" . $token);
        $this->uid = $uid;
        $this->Va=[];
        $this->orderWords=[];
        $this->orderWordsNum=[];
    }
   
    /*
    *  查询树状结构
    *  @author 小林《1814992057@qq.com》
    *  @datetime   2019/12/2
    *  @request    wid 组合规则的id
    *  @return     json 树状结构的组合规则
    * */
    public function select_tree($wid){
        $data = DB::table("q_word")->get()->toArray();

        foreach ($data as $k=>&$v){
            $data[$k]['title']=$v['id'].$v['title'];
        }


        $tree_data = $this->tree($data,$wid); //进行递归请求

        return [
            'status_code'      => 200,
            'message'     =>  '请求成功',
            'data' => $tree_data
        ];
    }

    /*
    *  递归查询树状结构 辅助定制函数 查询所属的组合规则下全部树状结构
    *  @author 小林《1814992057@qq.com》
    *  @datetime   2019/12/2
    *  @request    $data 全部的组合规则内容信息
    *  @request    $wid 组合规则的id
    *  @return     json 树状结构的组合规则
    * */
    public function tree($data,$wid=0){

        $newArray = array();

        foreach ($data as $k=>$v){
            if($v['fWordId']==$wid){
                $addV = $v;
                $addV['child']=$this->tree($data,$v['id']);
                $newArray[]=$addV;
            }
        }
        return $newArray;

    }
// 
    /*
    *  进行添加 组合规则
    *  @author 小林《1814992057@qq.com》
    *  @datetime   2019/12/2
    *  @request     String  title 组合规则的名称
    *  @request     Number  fWordId 父ID
    *  @request     Json  where {"wordId":123,"type":2,"value":3,"replate":"\u7537"}
    * */
    public function add_word(Request $request){

        $data = $request->only('title','fWordId','where','replace','qpid','orderWords');

        // if(!preg_match('/^[\w\x{4e00}-\x{9fa5}]{2,10}$/u',$data['title'])) return ThrowApiExc('20001');
        //fWordId不存在 格式为非字数字 长度不等于1
        if(!array_key_exists('fWordId',$data)||!preg_match('/^[\d]{1,10}$/u',$data['fWordId'])) return ThrowApiExc('32017');
        if(!array_key_exists('orderWords',$data)||$data['orderWords']==null) return ThrowApiExc('32027');
        if(!array_key_exists('qpid',$data)||$data['qpid']==null) return ThrowApiExc('32028');

        if(array_key_exists('where',$data)){
            $res = $this->Verification_where($data['where']);
            if($res==0) return ThrowApiExc(32018);
        }
        
        $res = DB::table('q_word')->insertGetId($data);


            if($res){
                return [
                    'status_code'      => 200,
                    'message'     =>  '提交成功',
                    'data' => $res
                ];
            }else{
                return [
                    'status_code'      => 200,
                    'message'     =>  '提交失败 联系后端开发',
                    'data' => $res
                ];
            }


        }

        /*
        *  进行修改 组合规则 wid 组合规则的id
        *  @author 小林《1814992057@qq.com》
        *  @datetime   2019/12/2
        *  @request     String  title 组合规则的名称
        *  @request     Number  fWordId 父ID
        *  @request     Json  where {"wordId":123,"type":2,"value":3,"replate":"\u7537"}
        * */
        public function update_word(Request $request,$wid){

            $data = $request->only('title','fWordId','description','where','replace','qpid','orderWords');
            // if(!preg_match('/^[\w\x{4e00}-\x{9fa5}]{2,10}$/u',$data['title'])) return ThrowApiExc('20001');
            //fWordId不存在 格式为非字数字 长度不等于1
            if(!array_key_exists('fWordId',$data)||!preg_match('/^[\d]{1,10}$/u',$data['fWordId'])) return ThrowApiExc('32017');
            if(!array_key_exists('orderWords',$data)||$data['orderWords']==null) return ThrowApiExc('32027');
            if(!array_key_exists('qpid',$data)||$data['qpid']==null) return ThrowApiExc('32028');
            if(array_key_exists('where',$data)){
                $res = $this->Verification_where($data['where']);
                if($res==0) return ThrowApiExc(32018);
            }
            $res = DB::table('q_word')->where('id',$wid)->update($data);


            if($res){
                return [
                    'status_code'      => 200,
                    'message'     =>  '提交成功',
                    'data' => $res
                ];
            }else{
                return [
                    'status_code'      => 200,
                    'message'     =>  '提交失败 联系后端开发',
                    'data' => $res
                ];
            }

        }

        /*
        *  进行删除 组合规则 wid 组合规则的id
        *  @author 小林《1814992057@qq.com》
        *  @datetime   2019/12/2
        * */
        public function delete_word($wid){

            $res = DB::table('q_word')->where('id',$wid)->delete();
            DB::table("q_word_json")->where('wid',$wid)->delete();
            return [
                'status_code'      => 200,
                'message'     =>  '删除成功',
                'data' => $res
            ];

        }
        /*
         *  添加组合规则的 表述方式
         *  @author 小林《1814992057@qq.com》
         *  @datetime   2019/12/2
         *  @request    JSON  json 表述方式的json数据
         *  @request    Int  type 是否使用状态 1使用 2关闭
         *
         * */
        public function addWordJson(Request $request,$wid){


            $data = $request->only('json','type');
            $putData = file_get_contents("php://input");
            $resultData = json_decode($putData,true);
            if(is_array($resultData)){
                //解析IOS提交的PUT数据
                $data['json']=$resultData['json'];
            }
            //orderId不存在 格式为非字数字 长度不等于1
            if(!array_key_exists('type',$data)||!preg_match('/^[\d]{1,10}$/u',$data['type'])) return ThrowApiExc('32002');

            $data['wid']=$wid;
            $res = DB::table('q_word_json')->insertGetId($data);

            if($res){
                return [
                    'status_code'      => 200,
                    'message'     =>  '提交成功',
                    'data' => $res
                ];
            }else{
                return [
                    'status_code'      => 200,
                    'message'     =>  '提交失败 联系后端开发',
                    'data' => $res
                ];
            }

        }

    /*
    *  修改组合规则的 表述方式
    *  @author 小林《1814992057@qq.com》
    *  @datetime   2019/12/2
    *  @request    Int  wordJsonId 表述方式的id
    *  @request    JSON  json 表述方式的json数据
    *  @request    Int  type 是否使用状态 1使用 2关闭
    *
    * */
    public function updateWordJson(Request $request,$wordJsonId){

        $data = $request->only('json','type');
        $putData = file_get_contents("php://input");
        $resultData = json_decode($putData,true);
        if(is_array($resultData)){
            //解析IOS提交的PUT数据
            $data['json']=$resultData['json'];
        }

        //orderId不存在 格式为非字数字 长度不等于1
        if(!array_key_exists('type',$data)||!preg_match('/^[\d]{1,10}$/u',$data['type'])) return ThrowApiExc('32002');



        $res = DB::table('q_word_json')->where("id",$wordJsonId)->update($data);

        if($res){
            return [
                'status_code'      => 200,
                'message'     =>  '提交成功',
                'data' => $res
            ];
        }else{
            return [
                'status_code'      => 200,
                'message'     =>  '提交失败 联系后端开发',
                'data' => $res
            ];
        }

    }

        /*
        *  删除组合规则的 表述方式
        *  @author 小林《1814992057@qq.com》
        *  @datetime   2019/12/2
        *  @request    Int  wordJsonId 表述方式的id
        *
        * */
        public function deleteWordJson($wordJsonId){

            $res = DB::table("q_word_json")->where('id',$wordJsonId)->delete();
            return [
                'status_code'      => 200,
                'message'     =>  '删除成功',
                'data' => $res
            ];
        }
        /*
         *  获取当前用户的某个问卷的word内容
         *  @author 小林《1814992057@qq.com》
         *  @datetime   2019/12/2
         *
         *
         * */
        public function outputWord(Request $request,$quid){



            $this->quid=$quid;
            $uid= $this->uid; //用户id

            $qu = DB::table("q_q_p_users as qqpu")  //获取用户当前问卷的信息
                ->select("qq.id as qqid","qq.title as qqtitle","qq.wid")
                ->leftJoin("q_questionnaire as qq","qq.id","=","qqpu.qid")
                ->where("qqpu.id",$quid)->first();
            $content = $this->out($qu['wid'],$quid);





//            if($this->Va!=[]){
//                return [
//                    'status_code'      => 330,
//                    'message'     =>  '未填写项',
//                    'data' => $this->Va
//                ];
//            }else{
                $pdfName = "pdf/".date("Y",time())."/".date("m",time())."/".date("d",time())."/".date("YmdHis", time()) . rand(1000, 9999) . rand(1000, 9999) . ".pdf";  //文件重命名
                $content2 = $content;
                // $content2  = str_replace($content2,"<b>","<div>");
                // $content2  = str_replace($content2,"</b>","</div>");
                $pdf = PDF::loadHtml("<!DOCTYPE html>
                <html>
                <head>
                    <meta charset='utf-8'>
                    <meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, viewport-fit=cover'/>
                    <link rel='ico' type='image/x-icon' href='static/favicon.ico'>
                    <link rel='shortcut icon' type='image/x-icon' href='static/favicon.ico'>
                    
                    <title>蜗牛家事</title>
                    <style type='text/css'>
                    @font-face{
                        font-family: 'Microsoft';
                        src:url('http://office365.aladdinlaw.com:3921/pdf/msyh.ttf');
                        font-weight: normal;
                        font-style: normal;
                    }
                    html{
                        font-family: 'Microsoft';
                    }
                    html::-webkit-scrollbar {
                        display: none;
                        overflow-y: scroll;
                    }
                    .el-loading-spinner{left: 50%!important;}
                    .el-form-item{margin-bottom:8px !important;}
                    .el-form--label-top .el-form-item__label{padding-bottom:0 !important;}
                    .el-date-editor.el-input, .el-date-editor.el-input__inner{width:100% !important;}
                    .el-cascader{width:100% !important;}
                    .el-select{width:100% !important;}
                    .el-dialog{width: 696px !important;}
                    .myconsult .el-carousel .el-carousel__container {height: 554px !important;}
                    .myconsult .el-carousel .el-carousel__container button:focus{outline: none;}
                    .home .el-carousel .el-carousel__container button:focus{outline: none;}
                    .mmin .el-carousel .el-carousel__container button:focus{outline: none;}
                    .mRegist .el-input--suffix .el-input__inner{border:none;padding:0}
                    .mRegist .el-form-item{margin-bottom: 0!important;}
                    .mRegist .el-form-item__content{font-size: 16px;color: #343434;}
                    .mLogin .el-input--suffix .el-input__inner{border:none;padding:0;height: 32px !important;line-height: 32px !important;}
                    .mLogin .el-form-item{margin-bottom: 0!important;}
                    .mLogin .el-form-item__content{font-size: 16px;color: #343434;line-height: 32px !important;}
                    .mLogin .el-menu--horizontal>.el-menu-item.is-active{color: #547ce0;border-bottom: 2px solid #547ce0;}
                    .mKnowledgeMin #outputwordmsg b{display: table !important;text-indent: 2em;}
                    .mKnowledgeMin .min .con p span{font-size: 14px !important;}
                    .w{width: 1200px; margin: 0 auto;}
                    .bg-color {
                        background: #f2f4f7;
                    }
                    
                    .shengcheng_w {
                        width: 1200px;
                        margin: 0 auto;
                    }
                    .min_title{width: 100%;text-align: center;font-size: 14px;color: #b7b7b7;padding-top: 17px;padding-bottom: 17px;border-bottom: 1px solid #d8d8d8;}
                    .min {
                        width: 650px;
                        height: 800px;
                        overflow-y: scroll;
                        /* margin: 0px auto; */
                        text-align: left;
                    }

                    ::-webkit-scrollbar {
                        width:1px;
                        background-color: #FFF;
                    }
                    .min_top {
                        width: 890px;
                        display: flex;
                        justify-content: space-between;
                        padding-top: 73px;
                        margin: 0 auto;
                    }

                    .min_bottom {
                        width: 890px;
                        display: flex;
                        justify-content: space-between;
                        padding-bottom: 80px;
                        margin: 0 auto;
                    }
                    </style>
                </head>
                <body>
                    <div>
                        <div class='w-full bg-color relative' v-loading='fullscreenLoading'>
                            <div class='shengcheng_w pt-10 pb-2'>
                                <div class='bg-white '>
                                    <div class='min' id='ces'>
                                    {$content}
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </body>
                <script>
                        var content = decodeHtml(document.getElementById('ces').innerHTML);
                        function decodeHtml(s) {
                        var HTML_DECODE = {
                            '<': '<',
                            '>': '>',
                            '&': '&',
                            ' ': ' ',
                            ''': '\'',
                            '©': ''

                            // Add more
                        };

                        var REGX_HTML_ENCODE = /'|&|'|<|>|[\x00-\x20]|[\x7F-\xFF]|[\u0100-\u2700]/g;

                        var REGX_HTML_DECODE = /&\w+;|&#(\d+);/g;

                        var REGX_TRIM = /(^\s*)|(\s*$)/g;

                        s = (s != undefined) ? s : '';
                        return (typeof s != 'string') ? s :
                            s.replace(REGX_HTML_DECODE,
                                    function ($0, $1) {
                                        var c = HTML_DECODE[$0];
                                        if (c == undefined) {
                                            // Maybe is Entity Number
                                            if (!isNaN($1)) {
                                                c = String.fromCharCode(($1 == 160) ? 32 : $1);
                                            } else {
                                                c = $0;
                                            }
                                        }
                                        return c;
                                    });
                    };
                    // document.write(content);
                    document.getElementById('ces').innerHTML=content;
                </script>
                </html>
                ");
                $pdf->save("pdf/123.pdf");
                $page = new PageController($request);
                DB::table("q_q_p_users")->where("id",$this->quid)->update(["content"=>$content,"pdfPath"=>$pdfName]);

                $wordFilePath=$page->get_word($quid);

                

                return [
                    'status_code'      => 200,
                    'message'     =>  '查询成功',
                    'data' => [
                        "content"=>str_replace("|||||","",$content),
                        "wordFilePath"=>$wordFilePath['data']
                    ]
                ];
//            }

        }



        /*
         *  获取当前用户的某个问卷的word内容
         *  @author 小林《1814992057@qq.com》
         *  @datetime   2019/12/2
         *
         *
         * */
        public function outputWordTS(Request $request,$quid){



            $this->quid=$quid;
            $uid= $this->uid; //用户id

            $qu = DB::table("q_q_p_users as qqpu")  //获取用户当前问卷的信息
                ->select("qq.id as qqid","qq.title as qqtitle","qq.wid")
                ->leftJoin("q_questionnaire as qq","qq.id","=","qqpu.qid")
                ->where("qqpu.id",$quid)->first();
            $content = $this->out($qu['wid'],$quid);
            Redis::setex("isqpid:".$quid ,10,0);
            Redis::setex("isnum:".$quid ,10,0);





//            if($this->Va!=[]){
//                return [
//                    'status_code'      => 330,
//                    'message'     =>  '未填写项',
//                    'data' => $this->Va
//                ];
//            }else{
                $pdfName = "pdf/".date("Y",time())."/".date("m",time())."/".date("d",time())."/".date("YmdHis", time()) . rand(1000, 9999) . rand(1000, 9999) . ".pdf";  //文件重命名
                $content2 = $content;
                // $content2  = str_replace($content2,"<b>","<div>");
                // $content2  = str_replace($content2,"</b>","</div>");
                $pdf = PDF::loadHtml("<!DOCTYPE html>
                <html>
                <head>
                    <meta charset='utf-8'>
                    <meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, viewport-fit=cover'/>
                    <link rel='ico' type='image/x-icon' href='static/favicon.ico'>
                    <link rel='shortcut icon' type='image/x-icon' href='static/favicon.ico'>
                    
                    <title>蜗牛家事</title>
                    <style type='text/css'>
                    @font-face{
                        font-family: 'Microsoft';
                        src:url('http://office365.aladdinlaw.com:3921/pdf/msyh.ttf');
                        font-weight: normal;
                        font-style: normal;
                    }
                    html{
                        font-family: 'Microsoft';
                    }
                    html::-webkit-scrollbar {
                        display: none;
                        overflow-y: scroll;
                    }
                    .el-loading-spinner{left: 50%!important;}
                    .el-form-item{margin-bottom:8px !important;}
                    .el-form--label-top .el-form-item__label{padding-bottom:0 !important;}
                    .el-date-editor.el-input, .el-date-editor.el-input__inner{width:100% !important;}
                    .el-cascader{width:100% !important;}
                    .el-select{width:100% !important;}
                    .el-dialog{width: 696px !important;}
                    .myconsult .el-carousel .el-carousel__container {height: 554px !important;}
                    .myconsult .el-carousel .el-carousel__container button:focus{outline: none;}
                    .home .el-carousel .el-carousel__container button:focus{outline: none;}
                    .mmin .el-carousel .el-carousel__container button:focus{outline: none;}
                    .mRegist .el-input--suffix .el-input__inner{border:none;padding:0}
                    .mRegist .el-form-item{margin-bottom: 0!important;}
                    .mRegist .el-form-item__content{font-size: 16px;color: #343434;}
                    .mLogin .el-input--suffix .el-input__inner{border:none;padding:0;height: 32px !important;line-height: 32px !important;}
                    .mLogin .el-form-item{margin-bottom: 0!important;}
                    .mLogin .el-form-item__content{font-size: 16px;color: #343434;line-height: 32px !important;}
                    .mLogin .el-menu--horizontal>.el-menu-item.is-active{color: #547ce0;border-bottom: 2px solid #547ce0;}
                    .mKnowledgeMin #outputwordmsg b{display: table !important;text-indent: 2em;}
                    .mKnowledgeMin .min .con p span{font-size: 14px !important;}
                    .w{width: 1200px; margin: 0 auto;}
                    .bg-color {
                        background: #f2f4f7;
                    }
                    
                    .shengcheng_w {
                        width: 1200px;
                        margin: 0 auto;
                    }
                    .min_title{width: 100%;text-align: center;font-size: 14px;color: #b7b7b7;padding-top: 17px;padding-bottom: 17px;border-bottom: 1px solid #d8d8d8;}
                    .min {
                        width: 650px;
                        height: 800px;
                        overflow-y: scroll;
                        /* margin: 0px auto; */
                        text-align: left;
                    }

                    ::-webkit-scrollbar {
                        width:1px;
                        background-color: #FFF;
                    }
                    .min_top {
                        width: 890px;
                        display: flex;
                        justify-content: space-between;
                        padding-top: 73px;
                        margin: 0 auto;
                    }

                    .min_bottom {
                        width: 890px;
                        display: flex;
                        justify-content: space-between;
                        padding-bottom: 80px;
                        margin: 0 auto;
                    }
                    </style>
                </head>
                <body>
                    <div>
                        <div class='w-full bg-color relative' v-loading='fullscreenLoading'>
                            <div class='shengcheng_w pt-10 pb-2'>
                                <div class='bg-white '>
                                    <div class='min' id='ces'>
                                    {$content}
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </body>
                <script>
                        var content = decodeHtml(document.getElementById('ces').innerHTML);
                        function decodeHtml(s) {
                        var HTML_DECODE = {
                            '<': '<',
                            '>': '>',
                            '&': '&',
                            ' ': ' ',
                            ''': '\'',
                            '©': ''

                            // Add more
                        };

                        var REGX_HTML_ENCODE = /'|&|'|<|>|[\x00-\x20]|[\x7F-\xFF]|[\u0100-\u2700]/g;

                        var REGX_HTML_DECODE = /&\w+;|&#(\d+);/g;

                        var REGX_TRIM = /(^\s*)|(\s*$)/g;

                        s = (s != undefined) ? s : '';
                        return (typeof s != 'string') ? s :
                            s.replace(REGX_HTML_DECODE,
                                    function ($0, $1) {
                                        var c = HTML_DECODE[$0];
                                        if (c == undefined) {
                                            // Maybe is Entity Number
                                            if (!isNaN($1)) {
                                                c = String.fromCharCode(($1 == 160) ? 32 : $1);
                                            } else {
                                                c = $0;
                                            }
                                        }
                                        return c;
                                    });
                    };
                    // document.write(content);
                    document.getElementById('ces').innerHTML=content;
                </script>
                </html>
                ");
                $pdf->save("pdf/123.pdf");
                $page = new PageController($request);
                DB::table("q_q_p_users")->where("id",$this->quid)->update(["content"=>$content,"pdfPath"=>$pdfName]);

                $wordFilePath=$page->get_wordTS($quid);

                

                return [
                    'status_code'      => 200,
                    'message'     =>  '查询成功',
                    'data' => [
                        "content"=>str_replace("|||||","",$content),
                        "wordFilePath"=>$wordFilePath['data']
                    ]
                ];
//            }

        }


        public function outputWordTS_content($quid){
                
        }




        public function Verification_word($wid,Request $request){
            $this->quid=quid($this->uid);

            $content = $this->out($wid,$this->quid);
            if($this->Va!=[]){
                return [
                    'status_code'      => 330,
                    'message'     =>  '未填写项',
                    'data' => $this->Va
                ];
            }else{
                return [
                    'status_code'      => 200,
                    'message'     =>  '查询成功',
                    'data' => $content
                ];
            }
        }


        public function out($wid,$quid,$fornum=false){

          
            $content="";
            $word = DB::table("q_word")->where("id",$wid)->first();
            $where = true;
            $replateArr = [];
            $iffor = false;
            $for = 1;

            $qpids = json_decode($word['qpid']);
            
            if($word['orderWords']&&$word['orderWords']!="[]"&&is_array(json_decode($word['orderWords']))){
                $this->orderWords[$word['id']]=json_decode($word['orderWords']);
            }
                if($qpids){
                foreach ($qpids as $k=>$v){
                    $this->Verification_answer($v,$fornum);
                }
            }

            if($word['where']){
                $linArr =0;
                foreach (json_decode($word['where']) as $k=>$v){
                    $qp = DB::table("q_q_p")->where("id",$v->qpid)->first();
                    
                    if(!property_exists($v,'replate')||$v->replate==""){ //非替换的时候
                        $where=[
                            [
                                "qua.quid",$quid
                            ],[
                                "qua.qpid",$qp['id']
                            ]
                        ];
                        if($fornum) $where[]=['qua.fornum',$fornum];
                        
    
                        $qu = DB::table("q_user_answer as qua")
                            ->select("qua.value","qqp.type","qua.id")
                            ->leftJoin("q_q_p as qqp",'qqp.id','=',"qua.qpid")
                            ->where($where)->first();


                        $linW= $this->word_where($qu['value'],$v->value,$v->type);
                        if($linW===false) $where=false;
                        if($linW===2) $linArr++;
                        // if($wid==13396){
                        //     var_dump($linW);
                        //     var_dump($qu['value'],$v->value,$v->type);
                        //     die;
                        // };
//                        var_dump($wid,$word['title'],$v->type);
                        if(!$where||$linArr>=count(json_decode($word['where']))) return;

                        
                        
                        
                        if($qu['type']==3){
                            $for = $qu['value'];
                            $iffor=true;
                        }




                    }else{

                            $replateArr[] = [
                                'qpid'=>$v->qpid,
                                'value'=>$v->value,
                                'replate'=>$v->replate
                            ];


                    }

                }
            }

                          
            $word = DB::table("q_word")->where("id",$wid)->first();

            $jsons = DB::table("q_word_json")->where("wid",$wid)->get();
            
            if($jsons){

                if(count($jsons)==0){
                    return ;
                }

                if(count($jsons)==1){
                    $json = $jsons['0']['json'];
                }else{

                    $json = $jsons[rand(0,count($jsons)-1)]['json'];
                }


                if($iffor){

                    $content .= $this->wordContent2($json,$replateArr,$quid,$for);

                }else{

                    $content.=$this->wordContent($json,$replateArr,$quid,$fornum);
                }

            }


            foreach ($this->orderWords as $kk=>$vv){
                foreach ($vv as $kkk=>$vvv){
                    if($vvv==$word['id']){

                        if(!array_key_exists($kk,$this->orderWordsNum)) $this->orderWordsNum[$kk]=1;

                        if(count($vv)==1){
                            $content="\n    ".$content;
                        }else{
                            $content="\n    ".$this->orderWordsNum[$kk].".".$content;
                        }
                        $this->orderWordsNum[$kk]++;
                    }
                }
            }

            return $content;



        }

        public function wordContent($json,$replateArr,$quid,$fornum=false){
            $content = $json;

            if (preg_match_all("~\{\{\s*(.*?)\s*\}\}~", $json, $arr)) ;

            $jsonArr = $arr[1];
      
            foreach ($jsonArr as $k=>$v){
                $arr = explode(",",$v);
                $linshiStr="";
              
                switch ($arr[0]){
                    case 1:  //标题
                        $linshiStr="<b>".$arr[1]."</b>";
                        break;
                    case 2://问题

                        $linshiStr=$this->problemValue($arr[1],$replateArr,$fornum);
                        break;
                    case 3://组合
                        $newJson = DB::table("q_word")->where("id",$arr[1])->first();
                        $linshiStr=$this->out($newJson['id'],$quid,$fornum);
                        break;
                    case 4://fornum

                        if($this->linshiFor==1){
                            $linshiStr="";
                        }else{
                            $linshiStr="(".$fornum.")";
                        }
                        break;
                    case 7:
                        // $linshiStr="<img src='./深圳胡律师.png'>";
                        $linshiStr="{{7}}";
                        break;
                    case 8:
                        $linshiStr="{{".$v."}}";
                        break;
                    case 9:
                        $linshiStr="{{".$v."}}";
                        break;
                    case 10:
                        $diyqpid=$arr[1];
                        $isNums = Redis::get("diyqpid:".$quid.":".$diyqpid);
                        if($diyqpid){
                            $isNums++;
                            Redis::setex("diyqpid:".$quid.":".$diyqpid,5,$isNums);
                            }else{
                            Redis::setex("diyqpid:".$quid.":".$diyqpid,5,1);
                            $isNums=1;
            
                            }
                        
                    $linshiStr=n2c($isNums);
                        break;
                    case 14:
                        $linshiStr="{{".$v."}}";
                        break;
                    case 15:
                        
                        $diyqpid=$arr[1];
                        $isNums = Redis::get("diyqpid:".$quid.":".$diyqpid);
                        if($diyqpid){
                            $isNums++;
                                Redis::setex("diyqpid:".$quid.":".$diyqpid,5,$isNums);
                            }else{
                                Redis::setex("diyqpid:".$quid.":".$diyqpid,5,1);
                                $isNums=1;
            
                            }
                            $linshiStr=$isNums;


                    break;
                    case 16:
                        $linshiStr="{{".$v."}}";
                        break;

                }

                $content=str_replace("{{".$v."}}",$linshiStr,$content);
            }



            return $content;

        }
       
    public function wordContent2($json,$replateArr,$quid,$fornum){

        $content = $json;
        if (preg_match_all("~\{\{\s*(.*?)\s*\}\}~", $json, $arr)) ;

        $jsonArr = $arr[1];
        
        foreach ($jsonArr as $k=>$v){
            $arr = explode(",",$v);
            $linshiStr="";
            switch ($arr[0]){
                case 1:  //标题
                    $linshiStr="<b>".$arr[1]."</b>";
                    break;
                case 2://问题
                    $linshiStr=$this->problemValue($arr[1],$replateArr,false);
                    break;
                case 3://组合
                    $this->linshiFor=$fornum;
 
                    for($i=1;$i<=$fornum;$i++){
                        $newJson = DB::table("q_word")->where("id",$arr[1])->first();
                        $linshiStr.=$this->out($newJson['id'],$quid,$i);
                    }
                    break;
                case 4://fornum
                    $linshiStr=$fornum;
                    break;
                case 10:
                    $diyqpid=$arr[1];
                    $isNums = Redis::get("diyqpid:".$quid.":".$diyqpid);
                    if($diyqpid){
                        $isNums++;
                        Redis::setex("diyqpid:".$quid.":".$diyqpid,5,$isNums);
                        }else{
                        Redis::setex("diyqpid:".$quid.":".$diyqpid,5,1);
                        $isNums=1;
                            
                        }
                        $linshiStr=n2c($isNums);
                    
                        

                        break;

                    break;
                case 15:
                    $diyqpid=$arr[1];
                    $isNums = Redis::get("diyqpid:".$quid.":".$diyqpid);
                    if($diyqpid){
                        $isNums++;
                        Redis::setex("diyqpid:".$quid.":".$diyqpid,10,$isNums);
                    }else{
                        Redis::setex("diyqpid:".$quid.":".$diyqpid,10,1);
                        $isNums=1;

                    }
                    $linshiStr=$isNums;
                    break;
                case 16:
                    $linshiStr="{{".$v."}}";
                    break;
            }
            $content=str_replace("{{".$v."}}",$linshiStr,$content);

        }



        return $content;

    }

        public function add_users_answer(Request $request){

            $data = $request->only('value','qpid');
            $data['userId']=3;


        }

        public function select($wid){

            $word = DB::table("q_word")->where('id',$wid)->first();
            $word['json']=DB::table("q_word_json")->where('wid',$wid)->get();
            if($word['where']){
                $word['where']=json_decode($word['where']);
                foreach ($word['where'] as $k=>&$v){
                    $res = DB::table("q_q_p as qqp")
                        ->select("qp.title","qa.label","qqp.id")
                        ->leftJoin("q_problem as qp","qqp.problemId","=","qp.id")
                        ->leftJoin("q_answer as qa","qp.id","=","qa.problemId")
                        ->where([
                            [
                                "qqp.id",$v->qpid
                            ],[
                                "qa.value",$v->value
                            ]
                        ])
                        ->first();
                    $v->title=$res['id']."|||".$res['title'];
                    $v->label=$res['label'];
                }
            }


            return [
                'status_code'      => 200,
                'message'     =>  '提交成功',
                'data' => $word
            ];
        }


        public function problemValue($problemId,$replateArr,$fornum=false)
        {
           
            $typeArr=[6,7,8,9];
            $problem = DB::table("q_q_p as qqp")
                ->select("qp.type as type",'qp.id as problemId')
                ->leftJoin("q_problem as qp","qqp.problemId","=","qp.id")
                ->where("qqp.id",$problemId)->first();
            $where = [
                [
                    "qpid",$problemId
                ],[
                    "quid",$this->quid
                ]
//                ,[
//                    "userId",$this->uid
//                ]
            ];
            if($fornum) $where[]=['fornum',$fornum];



            $value = DB::table("q_user_answer")->where($where)->first()['value'];


                $where=[];
                $whereValue=[];
            $this->Verification_answer($problemId,$fornum);

            if(!$value) return "";

                if(in_array($problem['type'],[7,9])){
                    $whereArr=json_decode($value);
                    foreach ($whereArr as $k=>$v){
                        $whereValue[]=$v;
                    }
                }else{
                    $whereValue[]=$value;
                }
            date_default_timezone_set("PRC");

            switch ($problem['type']){
                case $problem['type']>=6&&$problem['type']<=9:
                    $value = DB::table("q_answer")
                    ->where( "problemId",$problem['problemId'])
                    ->whereIn("value",$whereValue)
                    ->get();
                    $label="";
                    foreach ($value as $kk=>$vv){
                        foreach ($replateArr as $k=>$v){

                            if($v['value']==$vv['value']){
                                return $v['replate'];
                            }

                        }
                        if($label==""){
                            $label=$label.$vv['label'];
                        }else{
                            $label=$label."、".$vv['label'];
                        }
                    }


                return $label;
                break;
                case 3:
                    return date("Y年m月d日",strtotime($value));
                break;
                case 4://区间时间
                    $res = json_decode($value);
                    return date("Y年m月d日",strtotime($res[0]))."至".date("Y年m月d日",strtotime($res[1]));
                    break ;
                case 5://区间到日
                    $res = json_decode($value);
                    return date("H:i",strtotime($res[0]))."至".date("H:i",strtotime($res[1]));
                    break;
                case 14://区间到日
                    $res = json_decode($value);
                    if($res[1]=="市辖区") $res[1]="";
                    return $res[0].$res[1].$res[2];
                    break;
                default:
                    return $value;
                break;
            }

        }
        //验证是否有必填项没有填写
        public function Verification_answer($qpid,$fornum){

            $where=[["qua.qpid",$qpid],["qua.quid",$this->quid]];
            if($fornum) $where[]=["qua.fornum",$fornum];
            $res = DB::table("q_user_answer as qua")
                ->select("qua.value")
                ->where($where)
                ->first();


            if(!$res['value']||$res['value']==""||$res['value']==null){
                $res2 = DB::table("q_q_p")->where("id",$qpid)->first();
                if($res2['important']==1){

                    $qp = DB::table("q_q_p as qqp")
                        ->select("qp.title")
                        ->leftJoin("q_problem as qp","qp.id","qqp.problemId")
                        ->where("qqp.id",$qpid)->first();
                    $this->Va[]=[
                        'qpid'=>$qpid,
                        "problemTitle"=>$qp['title'],
                        'fornum'=>$fornum
                    ];
                }

            }
        }

        /*
        *  验证组合规则的where条件是否正确
        *  @author 小林《1814992057@qq.com》
        *  @datetime   2019/12/2
        *  @request    json where条件的json格式数据
        *  @return     Booleans 布尔值 true格式正确 false 格式错误
        * */
        public function Verification_where($json){
            $data = object_array(json_decode($json));

            $dataArr= ['qpid','type','value','replate'];
            foreach ($data as $k=>$v){
                if(count($v)!=4) return 0;
                foreach ($v as $kk=>$vv){
                    if(!in_array($kk,$dataArr)){
                        return 0;
                    }
                }
            }
            return 1;
        }



        public function word_where($value,$problemValue,$where){

            switch ($where){
                case "2": //小于
                    if($value < $problemValue){
                        return true;
                    }else{
                        return false;
                    }
                    break;
                case "5"://小于等于
                    if($value <= $problemValue){
                        return true;
                    }else{
                        return false;
                    }
                    break;
                case "3"://大于
                    if($value > $problemValue){
                        return true;
                    }else{
                        return false;
                    }
                    break;
                case "4"://大于等于
                    if($value >= $problemValue){


                        return true;
                    }else{
                        return false;
                    }
                    break;
                case "1"://等于
                    if($value == $problemValue){
                        return true;
                    }else{
                        return false;
                    }
                    break;
                case "6"://不等于
                    if($value != $problemValue){
                        return true;
                    }else{
                        return false;
                    }

                    break;
                case "7"://包含
                    $value=str_replace("[","",$value);
                    $value=str_replace("[","",$value);
                    $value=str_replace('"',"",$value);
                    $value=explode(",",$value);

                    if($problemValue)

                    if(is_array($value)){
                        if(in_array($problemValue,$value)){
                            return true;
                        }else{
                            return 2;
                        }
                    }else{
                        // var_dump($problemValue,$value);
                        // die;
                    }


                    break;
                case "8"://不等于空
                    if($value != null){
                        return true;
                    }else{
                        return false;
                    }
                    break;
                case "9"://或包含
                    break;
                case "10"://或等于
                    break;
                default:
                    if(!$value<$problemValue){
                        return true;
                    }else{
                        return false;
                    }
                    break;
            }

        }


        public function select_word(Request $request){




            $title = $request->title;

            if($title){
                $data=DB::table("q_word")->where("title","like","%".$title."%")->get()->toArray();
                foreach ($data as $k=>&$v){
                    $data[$k]['title']=$v['id'].$v['title'];
                }
                return [
                    'status_code'      => 200,
                    'message'     =>  '提交成功',
                    'data' => $data
                ];
            }else{
                return [
                    'status_code'      => 200,
                    'message'     =>  '提交成功',
                    'data' => ""
                ];
            }

        }

        public function demo_yanzheng(Request $request,$quid){
            $request->qid=DB::table("q_q_p_users")->where("id",$quid)->first()['qid'];
            $request->quid=$quid;
            $page = new PageController($request);
            $page_data =$page->returnQuestionnaireJson($request,$request->qpid);
            if(!array_key_exists("data",$page_data)){
                return [
                    'status_code'      => 200,
                    'message'     =>  '无验证项',
                    'data' => 1
                ];
            }

            $res=[];
            foreach ($page_data['data'] as $k=>$v){
                    $res= array_merge($res,$this->demo($v));
            }

            if($res!=[]){
                return [
                    'status_code'      => 330,
                    'message'     =>  '未填写项',
                    'data' =>$res
                ];
            }else{
                return [
                    'status_code'      => 200,
                    'message'     =>  '验证成功',
                    'data' =>$res
                ];
            }

        }

        

        public function  demo($data){
            $newdata = [];


            foreach ($data as $k=>$v) {
                if ($v == [] || !is_array($v)) continue;

                    if (array_key_exists("questions", $v)) {


                        // foreach($v['questions'] as $kk=>$vv){
                                $newdata = array_merge($newdata,$this->demo($v['questions']));
                            // }
                    }else if($v['answer']!=""&&$v['answer']!="[]"&&array_key_exists("childQuestion", $v)){
                        $answer = json_decode($v['answer']);
                        if(!is_array($answer)) continue;
                        foreach($v['childQuestion'] as $kk=>$vv){
                            if(in_array($kk,$answer)){
                                $newdata = array_merge($newdata,$this->demo($v['childQuestion'][$kk]));
                            }
                        }
                    }else if($v['answer']!=""&&$v['answer']!="[]"&&array_key_exists("grandson", $v)){
                        $answer = json_decode($v['answer']);
                        if(!is_array($answer)) continue;
                        foreach($v['grandson'] as $kk=>$vv){
                            if(in_array($kk,$answer)){
                                $newdata = array_merge($newdata,$this->demo($v['grandson'][$kk]));
                            }
                        }
                    } else {
                        if (array_key_exists("answer",$v)&&$v['answer'] != null) {
                            if(array_key_exists("requireQidAndAnswer",$v)){
                                $where = [];
                                $where = $this->if_requireQidAndAnswer($data,$v['requireQidAndAnswer']['id'],$v['requireQidAndAnswer']['answer']);
                                if(!$where) continue;
                            }


                            if (array_key_exists("childQuestion",$v) && $v['childQuestion'] != []) {
                                if (_checkAssocArray(array_keys($v['childQuestion']))) {
                                    $newdata = array_merge($newdata,$this->demo($v['childQuestion'], $v['answer']));
                                } else {
                                    if(array_key_exists($v['answer'],$v['childQuestion'])) $newdata = array_merge($newdata,$this->demo($v['childQuestion'][$v['answer']]));
                                }
                            }
                            if (array_key_exists("grandson",$v) && $v['grandson'] != []) {
                                if (_checkAssocArray(array_keys($v['grandson']))) {
                                    $newdata = array_merge($newdata,$this->demo($v['grandson'], $v['answer']));
                                } else {
                                    if(array_key_exists($v['answer'],$v['grandson'])) $newdata = array_merge($newdata,$this->demo($v['grandson'][$v['answer']]));
                                }
                            }
                        } else {
                            if(array_key_exists("requireQidAndAnswer",$v)){
                                $where = [];
                                $where = $this->if_requireQidAndAnswer($data,$v['requireQidAndAnswer']['id'],$v['requireQidAndAnswer']['answer']);
                                if (array_key_exists("isRequired", $v) && $v['isRequired'] == true&&$v['type']!="question"){

                                    if($where){
                                        $linshi=["title"=>$v['title'],"id"=>$v['id']];
                                        if(array_key_exists("fornum",$v)) $linshi["fornum"]=$v['fornum'];
                                        $newdata[]=$linshi;
                                    }
                                }

                            }else{
                                if (array_key_exists("isRequired", $v) && $v['isRequired'] == true&&$v['type']!="question"){
                                    $linshi=["title"=>$v['title'],"id"=>$v['id']];
                                    if(array_key_exists("fornum",$v)) $linshi["fornum"]=$v['fornum'];
                                    $newdata[]=$linshi;
                                }
                            }


                        }

                    }

            }

            return $newdata;
        }

        public function if_requireQidAndAnswer($data,$id,$answer){
            $where = false;
            foreach ($data as $k=>$v){
                if(array_key_exists("id",$v)){
                    if($v['id']==$id&&$v['answer']==$answer){
                        $where = true;
                    }
                }else{
                    $where = true;
                }
            }
            return $where;
        }

        /**
         * 获取改协议下的组合规则 完整版
         */

        public function va_word_all($wid){
            $content = $this->word_all($wid);
            $_SESSION['word_all_'.$wid]=$content;
        }
        public function word_all($wid){
            $word = DB::table("q_word")->where("id",$wid)->first();
            $jsons = DB::table("q_word_json")->where("wid",$wid)->get();

            if($jsons){

                if(count($jsons)==0){
                    return ;
                }

                if(count($jsons)==1){
                    $json = $jsons['0']['json'];
                }else{

                    $json = $jsons[rand(0,count($jsons)-1)]['json'];
                }
            }
            if (preg_match_all("~\{\{\s*(.*?)\s*\}\}~", $json, $arr)) ;


            $jsonArr = $arr[1];
            $content =$json;
            foreach ($jsonArr as $k=>$v){
                $arr = explode(",",$v);
                $linshiStr="";

                switch ($arr[0]){
                    case 3://组合
                        $linshiStr = $this->word_all($arr[1]);
                        $content=str_replace("{{".$v."}}",$linshiStr,$content);
                        break;
                }

            }

            return $content;
        }

        //sop获取单独部分生成内容
        public function sopWord(Request $request){
            $data=$request->only("wid",'quid');

            $this->quid=$data['quid'];
            $content = $this->out($data['wid'],$data['quid']);

            return [
                'status_code'      => 200,
                'message'     =>  '查询成功',
                'data' => $content
            ];
        }

}
